#include "audio.h"
#include "stdio.h"
#include "math.h"
#include "stm32_dsp.h"
#include "table_fft.h"

uint16_t adc_Buff[ADC_BUF_LEN] = {0};
__IO uint8_t AdcConvEnd = 0;
float voltage_Buff[ADC_BUF_LEN] = {0};
uint32_t FFT_Input[ADC_BUF_LEN] = {0};
uint32_t FFT_Output[ADC_BUF_LEN] = {0};
uint32_t FFT_Mag[ADC_BUF_LEN / 2] = {0};
float freq = 0;

void audio_Init()
{
    HAL_TIM_Base_Start(&htim3);
    HAL_TIM_Base_Start(&htim3);
}

void audio_Get()
{
    uint16_t i;

    AdcConvEnd = 0;
    HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adc_Buff, ADC_BUF_LEN);
    while (!AdcConvEnd)
        ;
    for (i = 0; i < ADC_BUF_LEN; i++)
    {
        //voltage_Buff[i] = adc_Buff[i] * (3.3 / 4096.0);
        FFT_Input[i] = (uint32_t)adc_Buff[i];
    }

    // for (i = 0; i < ADC_BUF_LEN; i++)
    // {
    //     printf("%.3f\r\n", voltage_Buff[i]);
    // }
}

/*
 *      获取谐波幅值
 */
void GetPowerMag()
{
    signed short lX, lY;
    float X, Y, Mag;
    unsigned short i;

    for (i = 0; i < ADC_BUF_LEN / 2; i++)
    {
        lX = (FFT_Output[i] << 16) >> 16;
        lY = (FFT_Output[i] >> 16);

        X = ADC_BUF_LEN * ((float)lX) / 32768;
        Y = ADC_BUF_LEN * ((float)lY) / 32768;

        Mag = sqrt(X * X + Y * Y) / ADC_BUF_LEN;

        if (i == 0)
            FFT_Mag[i] = (unsigned long)(Mag * 32768);
        else
            FFT_Mag[i] = (unsigned long)(Mag * 65536);
    }
}

void FFT()
{
    int i;
    int MAX_temp_buff = 0, MAX_temp_n = 0;
    audio_Get();
    cr4_fft_1024_stm32(FFT_Output, FFT_Input, ADC_BUF_LEN);
    GetPowerMag();
    FFT_Mag[0] = 0; // 去掉直流分量
    for (i = 0; i < ADC_BUF_LEN / 2; i++)
    {
        if (FFT_Mag[i] > MAX_temp_buff)
        {
            MAX_temp_buff = FFT_Mag[i];
            MAX_temp_n = i;
        }
    }
    freq = MAX_temp_n*(100000.0/1024.0);
}
